<template>
  <view class="contact-edit-container">
    <!-- 内容编辑区 -->
    <view class="content-container">
      <!-- 基本信息 -->
      <view class="section">
        <text class="section-title">基本信息</text>
        <input 
          class="input-field"
          v-model="formData.name"
          placeholder="姓名（必填）"
          maxlength="20"
        />
        <input 
          class="input-field"
          v-model="formData.relation"
          placeholder="关系（如：朋友、同事）"
          maxlength="20"
        />
        <view class="birthday-field">
          <text>生日：</text>
          <picker 
            mode="date" 
            :value="formData.birthday || ''"
            @change="handleBirthdayChange"
          >
            <view class="picker">
              {{ formData.birthday || '选择日期' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 特征列表 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">特征记录</text>
          <view class="add-btn" @click="openFeatureDialog">
            <uni-icons type="plus" size="20" color="#2775b6"></uni-icons>
          </view>
        </view>
        
        <view 
          v-for="(feature, index) in formData.features"
          :key="feature.id"
          class="feature-card"
        >
          <text class="feature-text">{{ feature.text }}</text>
          <uni-icons 
            type="trash" 
            size="20" 
            color="#EE3F4D"
            @click="removeFeature(index)"
          ></uni-icons>
        </view>

        <view v-if="formData.features.length === 0" class="empty-tip">
          <uni-icons type="info" size="20" color="#999"></uni-icons>
          <text>点击添加特征记录</text>
        </view>
      </view>
    </view>

    <!-- 底部保存按钮 -->
    <view class="footer">
      <button class="save-btn" @click="handleSave">保存联系人</button>
    </view>

    <!-- 添加特征弹窗 -->
    <uni-popup ref="featureDialog" type="dialog">
      <uni-popup-dialog 
        mode="input"
        title="添加特征"
        placeholder="输入特征描述"
        :maxlength="500"
        @confirm="addFeature"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useCognitionStore } from '@/stores/cognitionStore'

const cognitionStore = useCognitionStore()
const featureDialog = ref(null)

const formData = ref({
  id: '',
  name: '',
  relation: '',
  birthday: '',
  features: [],
  updatedAt: ''
})

// 加载数据
onLoad((query) => {
  if (query.id) {
    const record = cognitionStore.contents['人际'].find(item => item.id === query.id)
    if (record) {
      formData.value = {
        id: record.id,
        name: record.name || '',
        relation: record.relation || '',
        birthday: record.birthday || '',
        features: record.features ? [...record.features] : [],
        updatedAt: record.updatedAt || ''
      }
    }
  } else {
    formData.value.id = Date.now().toString()
  }
})

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 保存数据
const handleSave = () => {
  if (!formData.value.name.trim()) {
    uni.showToast({ title: '请输入姓名', icon: 'none' })
    return
  }

  const recordData = {
    id: formData.value.id,
    name: formData.value.name.trim(),
    relation: formData.value.relation.trim(),
    birthday: formData.value.birthday,
    features: formData.value.features,
    updatedAt: new Date().toISOString()
  }

  if (cognitionStore.contents['人际'].some(item => item.id === recordData.id)) {
    cognitionStore.updateContent(recordData.id, recordData)
  } else {
    cognitionStore.addContent(recordData)
  }

  uni.showToast({ title: '保存成功' })
  setTimeout(handleBack, 1500)
}

// 生日选择
const handleBirthdayChange = (e) => {
  formData.value.birthday = e.detail.value
}

// 打开特征弹窗
const openFeatureDialog = () => {
  featureDialog.value?.open()
}

// 添加特征
const addFeature = (text) => {
  if (!text || !text.trim()) return
  
  const newFeature = {
    id: Date.now().toString(),
    text: text.trim(),
    createdAt: new Date().toISOString()
  }
  
  if (!formData.value.features) {
    formData.value.features = []
  }
  
  formData.value.features.unshift(newFeature)
  featureDialog.value?.close()
}

// 删除特征
const removeFeature = (index) => {
  uni.showModal({
    title: '删除特征',
    content: '确定删除这条特征吗？',
    success: ({ confirm }) => {
      if (confirm) {
        formData.value.features.splice(index, 1)
      }
    }
  })
}
</script>

<style scoped>
.contact-edit-container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5fbfe;
  display: flex;
  flex-direction: column;
}

.content-container {
  flex: 1;
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(135, 206, 235, 0.1);
  margin-bottom: 20rpx;
}

.section {
  margin-bottom: 40rpx;
}

.section-title {
  display: block;
  font-size: 30rpx;
  font-weight: bold;
  color: #2775b6;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid rgba(135, 206, 235, 0.3);
}

.input-field {
  font-size: 28rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  border: 1rpx solid rgba(135, 206, 235, 0.3);
}

.birthday-field {
  display: flex;
  align-items: center;
  padding: 20rpx;
  font-size: 28rpx;
}

.picker {
  margin-left: 20rpx;
  color: #2775b6;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-btn {
  padding: 8rpx;
  border-radius: 50%;
  background-color: rgba(39, 117, 182, 0.1);
}

.feature-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  margin-bottom: 16rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  border-left: 4rpx solid #87CEEB;
}

.feature-text {
  font-size: 28rpx;
  flex: 1;
}

.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  color: #999;
  font-size: 26rpx;
  gap: 10rpx;
}

.footer {
  padding: 20rpx;
  background-color: white;
  border-radius: 16rpx;
  box-shadow: 0 -2rpx 8rpx rgba(135, 206, 235, 0.1);
}

.save-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #2775b6;
  color: white;
  font-size: 30rpx;
  border-radius: 12rpx;
  border: none;
}

.save-btn:active {
  background-color: #1a5c96;
}
</style>